import React, { useState } from 'react'
import Icon from '@/components/Icon'

import styles from './index.module.scss'
import Channels from './components/Channels/Channels'
import { Popup, Tabs } from 'antd-mobile'
import useInitialState from '@/hooks/useInitialState'
import {
  getUserChannel,
  changeActive,
  getAllChannel
} from '@/store/actions/home'
import { useDispatch } from 'react-redux'
import ArticleList from './components/ArticleList/ArticleList'
import { useHistory } from 'react-router'

const Home = () => {
  const history = useHistory()
  // 获取频道管理页面数据
  const { userChannels, active } = useInitialState(getUserChannel, 'home')
  const dispatch = useDispatch()
  const onchange = (channelId: string) => {
    dispatch(changeActive(channelId))
  }
  // 控制频道管理页显示与隐藏
  const [visible, setVisible] = useState(false)

  const show = () => {
    setVisible(true)
  }
  const hide = () => {
    setVisible(false)
  }
  // 获取所有频道
  useInitialState(getAllChannel, 'home')
  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      <Tabs
        onChange={onchange}
        className="tabs"
        activeKey={active}
        activeLineMode="fixed">
        {userChannels.length > 0 &&
          userChannels.map((item) => (
            <Tabs.Tab forceRender title={item.name} key={item.id}>
              <ArticleList channelId={item.id.toString()} />
            </Tabs.Tab>
          ))}
      </Tabs>
      <div className="tabs-opration">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={show} />
      </div>
      {/* 从左边过来 */}
      <Popup position="left" visible={visible}>
        <Channels hide={hide} />
      </Popup>
    </div>
  )
}

export default Home
